<template>
  <div class="product-detail-container">
    <div v-if="loading" class="loading">
      <el-skeleton :rows="10" animated />
    </div>
    
    <div v-else-if="product" class="product-detail">
      <el-row :gutter="40">
        <el-col :span="12">
          <div class="product-image">
            <img :src="product.image || '/default-product.jpg'" :alt="product.name" />
          </div>
        </el-col>
        
        <el-col :span="12">
          <div class="product-info">
            <h1>{{ product.name }}</h1>
            <div class="price">¥{{ product.price }}</div>
            <div class="category">分类：{{ product.category }}</div>
            <div class="description">{{ product.description }}</div>
            
            <div class="quantity-selector">
              <span>数量：</span>
              <el-input-number 
                v-model="quantity" 
                :min="1" 
                :max="product.stock || 999"
                size="large"
              />
            </div>
            
            <div class="actions">
              <el-button 
                type="primary" 
                size="large" 
                @click="addToCart"
                :loading="addingToCart"
                :disabled="!userStore.isAuthenticated()"
              >
                加入购物车
              </el-button>
              <el-button 
                type="danger" 
                size="large" 
                @click="buyNow"
                :loading="buying"
                :disabled="!userStore.isAuthenticated()"
              >
                立即购买
              </el-button>
            </div>
            
            <div v-if="!userStore.isAuthenticated()" class="login-tip">
              <el-alert 
                title="请先登录后再进行购买" 
                type="warning" 
                :closable="false"
                show-icon
              />
            </div>
          </div>
        </el-col>
      </el-row>
      
      <!-- 商品详细信息 -->
      <div class="product-details">
        <el-tabs v-model="activeTab">
          <el-tab-pane label="商品详情" name="details">
            <div class="detail-content">
              <h3>商品规格</h3>
              <el-descriptions :column="2" border>
                <el-descriptions-item label="商品名称">{{ product.name }}</el-descriptions-item>
                <el-descriptions-item label="商品分类">{{ product.category }}</el-descriptions-item>
                <el-descriptions-item label="商品价格">¥{{ product.price }}</el-descriptions-item>
                <el-descriptions-item label="库存数量">{{ product.stock || '充足' }}</el-descriptions-item>
                <el-descriptions-item label="商品描述" :span="2">{{ product.description }}</el-descriptions-item>
              </el-descriptions>
            </div>
          </el-tab-pane>
          
          <el-tab-pane label="用户评价" name="reviews">
            <div class="reviews-content">
              <p>暂无用户评价</p>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
    
    <div v-else class="not-found">
      <el-empty description="商品不存在" />
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useUserStore } from '@/stores/user';
import request from '@/utils/request';
import { ElMessage } from 'element-plus';

export default {
  name: 'ProductDetail',
  setup() {
    const route = useRoute();
    const router = useRouter();
    const userStore = useUserStore();
    
    const product = ref(null);
    const loading = ref(true);
    const error = ref(null);
    const quantity = ref(1);
    const addingToCart = ref(false);
    const buying = ref(false);
    const activeTab = ref('details');

    const fetchProduct = async () => {
      try {
        loading.value = true;
        const response = await request.get(`/products/${route.params.id}`);
        
        if (response.code === 200) {
          product.value = response.data;
        } else {
          error.value = response.message || '获取商品信息失败';
        }
      } catch (err) {
        console.error('获取商品信息失败:', err);
        error.value = '获取商品信息失败，请重试';
      } finally {
        loading.value = false;
      }
    };

    const addToCart = async () => {
      if (!userStore.isAuthenticated()) {
        ElMessage.warning('请先登录');
        router.push('/login');
        return;
      }

      addingToCart.value = true;
      try {
        const response = await request.post('/cart/items', null, {
          params: {
            userId: userStore.userId,
            productId: product.value.id,
            quantity: quantity.value
          }
        });

        if (response.code === 200) {
          ElMessage.success('已添加到购物车');
        } else {
          ElMessage.error(response.message || '添加失败');
        }
      } catch (error) {
        console.error('添加购物车失败:', error);
        ElMessage.error('添加失败，请重试');
      } finally {
        addingToCart.value = false;
      }
    };

    const buyNow = async () => {
      if (!userStore.isAuthenticated()) {
        ElMessage.warning('请先登录');
        router.push('/login');
        return;
      }

      buying.value = true;
      try {
        const cartResponse = await request.post('/cart/items', null, {
          params: {
            userId: userStore.userId,
            productId: product.value.id,
            quantity: quantity.value
          }
        });
        
        if (cartResponse.code === 200) {
          ElMessage.success('已添加到购物车');
          router.push('/cart');
        } else {
          ElMessage.error(cartResponse.message || '添加失败');
        }
      } catch (error) {
        ElMessage.error('购买失败: ' + (error.response?.data?.message || '网络错误'));
      } finally {
        buying.value = false;
      }
    };

    onMounted(() => {
      fetchProduct();
    });

    return {
      product,
      loading,
      error,
      quantity,
      addingToCart,
      buying,
      activeTab,
      userStore,
      addToCart,
      buyNow
    };
  }
};
</script>

<style scoped>
.product-detail-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.loading {
  padding: 40px;
}

.product-detail {
  background: white;
  border-radius: 8px;
  padding: 30px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.product-image {
  text-align: center;
}

.product-image img {
  max-width: 100%;
  max-height: 400px;
  object-fit: cover;
  border-radius: 8px;
}

.product-info h1 {
  margin: 0 0 20px 0;
  color: #333;
  font-size: 24px;
}

.price {
  font-size: 28px;
  color: #e74c3c;
  font-weight: bold;
  margin: 15px 0;
}

.category {
  color: #666;
  margin: 10px 0;
}

.description {
  color: #666;
  line-height: 1.6;
  margin: 15px 0;
}

.quantity-selector {
  margin: 20px 0;
  display: flex;
  align-items: center;
  gap: 10px;
}

.actions {
  margin: 30px 0;
  display: flex;
  gap: 15px;
}

.login-tip {
  margin-top: 20px;
}

.product-details {
  margin-top: 40px;
}

.detail-content {
  padding: 20px 0;
}

.reviews-content {
  padding: 20px 0;
  text-align: center;
  color: #999;
}

.not-found {
  text-align: center;
  padding: 60px 20px;
}
</style>